import { FileListItem } from 'element-ui/types/upload'

// Filter for adding cdn address to static resources url
function resourceFilter (url: string | null) {
  if (url === null || url === '') return ''

  const re = /^(\/static\/|http)./
  if (re.test(url)) return url

  const baseUrl = process.env.VUE_APP_BASE_API_CDN || '/static/'
  return baseUrl + url
}

// Filter for adding cdn address to static resources url array
function resourcesFilter (urls: string[] | null) {
  if (urls === null) return []

  const re = /^(\/static\/|http)./

  const baseUrl = process.env.VUE_APP_BASE_API_CDN || '/static/'
  urls.forEach((u, i) => {
    if (!re.test(u)) { urls[i] = baseUrl + u }
  })
  return urls
}

function imageFilenameFilter (url: string) {
  const re = /\/((\w|-|_)+\.(?:png|jpg))$/i
  const urlMatch = url.match(re)
  if (urlMatch) {
    return urlMatch[1]
  }
}

function elFileListFilter (filePathList: string[] | null): FileListItem[] {
  if (filePathList === null) return []
  const fileList: FileListItem[] = []
  const re = /\/((\w|-|_)+\.\w+)$/i
  filePathList.forEach(path => {
    const urlMatch = path.match(re)
    if (urlMatch) {
      fileList.push({
        name: urlMatch[1],
        url: resourceFilter(path)
      })
    }
  })
  return fileList
}

function audioDurationFilter (secs: number) {
  const minutes = Math.floor(secs / 60) || 0
  const seconds = (secs - minutes * 60) || 0

  return minutes + ':' + ('00' + Math.floor(seconds)).slice(-2)
}

export { resourceFilter, resourcesFilter, imageFilenameFilter, elFileListFilter, audioDurationFilter }
